//var getIp = 'http://4scafe.carnettong.com';// 双胜
var getIp = 'http://carnt.carnettong.com:8088';// 线上
$(function() {
	FastClick.attach(document.body);
});
var num=100;
var speed=2000; //一个红包从生产到消失的时间
var pageRuinTime=15;
var getPageNum=0;  //抢到的红包数
var allP=0;
var objs={
	GRADEONE:0,
	GRADETWO:0,
	GRADETHR:0,
	GRADEFOUR:0,
};//提交数据
$('.times').text(pageRuinTime);
//创建红包
function createdDom(createObj){
	var page='';
	if(createObj.AMOUNT<1){
		page=$('<span class="pages pages1" data-num='+createObj.AMOUNT+'></span>');
	}else if(createObj.AMOUNT==1){
		page=$('<span class="pages pages2" data-num='+createObj.AMOUNT+'></span>');
	}
	var allWidth=$('.ruinMain').outerWidth();//红包区域宽度
	var pageHeight=80;
	var pageWidth=80;
	var left=Math.random()*(allWidth-pageWidth);
	var height=$('.ruinMain').outerHeight()-pageHeight;//可运动的高度
	var rotates=(Math.random()*2-1)*60;
	if(pageRuinTime>0){
		$('.ruinMain').append(page);
	}
	$(page).css({'left':left,'top':-pageHeight,'transform':'rotate('+rotates+'deg)'});
	$(page).animate({top:height,'transform':'rotate(1800deg)'},speed,'linear',function(){
		$(this).remove();
	});
	
}
function init(arr){
	// 准备创建红包
	var pageNum=0;
	var newArr=[];
	var createSpeed=(pageRuinTime*1000)/num;
	for(var i=0;i<arr.length;i++){
		pageNum+=arr[i].NUM;
	}
	var times=setInterval(function(){
		var index=Math.floor((Math.random()*7/2));
		var createObj={};
		if(arr[index].NUM<=0){
			for(var j=0;j<arr.length;j++){
				if(arr[j].NUM>0){
					createObj=arr[j];
					arr[j].NUM--;
					break;
				}
			}
		}else{
			createObj=arr[index];
			arr[index].NUM--;
		}
		createdDom(createObj);
		pageNum--;
		if(pageNum<=0){
			clearInterval(times);
		}
	},createSpeed);

	//控制顶部的倒计时
	var downTime=setInterval(function(){
		pageRuinTime--;
		$('.times').text(pageRuinTime);
		if(pageRuinTime<=0){
			console.log("获得"+allP.toFixed(2));
			getVoucher(allP.toFixed(1));
			$('.ruinMain .pages').remove();
			clearInterval(downTime);
		}
	},1000)
}
function start(arr){
	$('.downStart1').addClass('sport');
	$('.downStart1').show();
	setTimeout(function(){
		$('.downStart2').addClass('sport');
		$('.downStart1').hide();
		$('.downStart2').show();
	},1000)
	setTimeout(function(){
		$('.downStart3').addClass('sport');
		$('.downStart2').hide();
		$('.downStart3').show();
	},2000)
	setTimeout(function(){
		$('.downStart3').hide();
		init(arr);
	},3000)
}
$('.ruinMain').on('click','.pages',function(event){
	getPageNum++;
	var nums=$('<em class="selectPrice">'+'+'+$(event.target).data('num')+'</em>')
	$('.ruinMain').append(nums);
	$('.selectPrice').css({'top':event.clientY,'left':event.clientX});
	setTimeout(function(){
		$(nums).remove();
	},500);
	if($(event.target).data('num')==0.1){
		objs.GRADEONE++
	}else if($(event.target).data('num')==0.2){
		objs.GRADETWO++
	}else if($(event.target).data('num')==0.3){
		objs.GRADETHR++
	}else if($(event.target).data('num')==1){ 
		objs.GRADEFOUR++
	}
	$('.getPage').text('已抢中'+getPageNum+'个红包');
	allP+=Number($(event.target).data('num'));
	$(event.target).remove();
})
//获取红包的详细
$.ajax({
	url : getIp + '/CARNT/TempActivityWeb/rainNotice',
    type : "post",
    dataType : "json",
    data : {
    	PHONE:_Global_=='web'?getCookie('userName'):getCookie('phone')
    },
    success:function(data){
    	if(data.STATUS_CODE==1){
    		if(data.ISRAIN==1&&data.ISPARTAKE==0){
    			start(data.AMOUNTARR);
    		}else if(data.ISRAIN==0){
    			promptBox('红包雨还未开始',' ',function(){
    				if(_Global_==='app'){
						action(20171101);
					}else{
						location.href='./main.html';
					}
    			});
    		}else if(data.ISPARTAKE==1){
    			promptBox('该时段你已经抢过',' ',function(){
    				if(_Global_==='app'){
						action(20171101);
					}else{
						location.href='./main.html';
					}
    			});
    		}
    	}
    }
})
function filterTime(val){
	var year=new Date(val).getFullYear();
	var month=new Date(val).getMonth()+1;
	var day=new Date(val).getDate();
	return year+'-'+month+'-'+day;
}
function getVoucher(amount){
	objs.PHONE=_Global_=='web'?getCookie('userName'):getCookie('phone');
	objs.COMPID='0';
	objs.SUBJECT='通用券';
	objs.RMK='通用券';
	objs.AMOUNT=amount;
	if(amount>0){
		$.ajax({
		url : getIp + '/CARNT/TempActivityWeb/rainSendCashVol',
	    type : "post",
	    dataType : "json",
	    data :objs,
	    success:function(data){
	    	if(data.STATUS_CODE==1){
	    		var voucherHtml='<div class="voucerAlert">'+
					'<div class="close1" onclick="closeVoucher()"></div>'+
					'<div class="vouchers">'+
						'<div class="voucherLeft">'+
							'<label>￥</label>'+
							'<span>'+data.AMOUNT+'</span>'+
						'</div>'+
						'<div class="voucherRight">'+
							'<h1>'+data.SUBJECT+'</h1>'+
							'<p>有效期至：'+filterTime(data.EXP_DATE)+'</p>'+
							'<h2>'+data.REMARK+'</h2>'+
						'</div>'+
					'</div>'+
					'<p>该券可在车网通平台使用</p>'+
					'<div class="btns btnsUse" onclick="btnsUse()"></div>'+
				'</div>';
				if(data.AMOUNT>0){
					$('.mask').show();
				    $('body').append(voucherHtml);
				}else{
					
				}
				
	    	}
	    }
	})
}else{
			promptBox('你一个都没抢中哦',' ',function(){
	    				if(_Global_==='app'){
							action(20171101);
						}else{
							location.href='./main.html';
						}
	    			});
					$('.mask').show();
	}
	
}
function closeVoucher(){
	$('.mask').hide();
	$('.voucerAlert').remove();
	if(_Global_==='app'){
		action(20171101);
	}else{
		location.href='./main.html';
	}
}
function btnsUse(){
	$('.mask').hide();
	$('.voucerAlert').remove();
	openHome();
}
function promptBox(text1, text2, func) {
	var promptB = $('.promptBox');
	promptB.find('.firstary').text(text1);
	if ( text2 ) {
		promptB.find('.secondary').text(text2);
	}
	promptB.show();
	$('.mask').show();
	promptB.find('.iKnow').on('click',function(){
		promptB.hide();
		$('.mask').hide();
		func && func();
	})
}



// ----------------------------------------------------------------- 以下是分享部分
//分享记录
function saveRecord(actId, type) {
var json = {
	'ACT_ID': actId,
	'SHARE_TYPE': type,
	'MOBILE': _Global_ == 'web' ? getCookie('userName') : phone
}
$.ajax({
	type: "post",
	async: false,
	dataType: "json",
	url: getIp + "/CARNT/Act/createShareRecord.action",
	data: json,
	success: function() {}
});
}
// 点击数
var json = {
'actId': 20171103
}

$.ajax({
type: "post",
async: false,
dataType: "json",
url: getIp + "/CARNT/Act/updateActClick.action",
data: json,
success: function(data) {
	//slert("ok");
}
})
var title;
var desc;
var imgUrl;
var linkUrl;
//分享文案
$.ajax({
type: "post",
async: false,
dataType: "json",
url: getIp + "/CARNT/ActWeb/getActivityById.action",
data: {
	ACT_ID: '20171103'
},
success: function(data) {
	title = data.RESULT_DATA[0].SHARE_TITLE;
	desc = data.RESULT_DATA[0].SHARE_CONTENT;
	imgUrl = data.RESULT_DATA[0].SHARE_ICON;
	linkUrl = data.RESULT_DATA[0].LINK_URL;
	document.title = title;
}
});
//获取分享的文案
var timestamp;
var nonceStr;
var signature;
//这个URL是你当前页面的url
var json = {
'url': location.href
}
var u = navigator.userAgent;
var isAndroids = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
var isiOSs = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
var urls='';
var appid='';
if(isAndroids){
	urls='../../OAuth/getAccess_token.action';
	appid='wxf71262a112685c25';
}else if(isiOSs){
	urls='../../OAuth/getAccess_tokenIPHONE.action';
	appid='wx054c6f61cacfa911';
}
$.ajax({
type: "post",
async: false,
dataType: "json",
url: urls,
data: json,
success: function(data) {
	timestamp = data.NOW_TIME;
	nonceStr = data.NONCESTR;
	signature = data.SKEY;
	wx.config({
		debug: false, // 开启调试模式,false调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		appId: appid, // 必填，公众号的唯一标识
		timestamp: timestamp, // 必填，生成签名的时间戳
		nonceStr: nonceStr, // 必填，生成签名的随机串
		signature: signature, // 必填，签名，见附录1
		jsApiList: [
			'onMenuShareTimeline',
			'onMenuShareAppMessage',
			'hideOptionMenu',
			'showOptionMenu'
		]
	});
}
});
wx.ready(function() {

// 分享给朋友
wx.onMenuShareAppMessage({
	title: title,
	desc: desc,
	link: linkUrl,
	imgUrl: imgUrl,
	trigger: function(res) {},
	success: function(res) {
		saveRecord(20171103, 1);
	},
	cancel: function(res) {},
	fail: function(res) {
		alert(JSON.stringify(res));
	}
});

//分享朋友圈
wx.onMenuShareTimeline({
	title: title,
	desc: desc,
	link: linkUrl,
	imgUrl: imgUrl,
	trigger: function(res) {

	},
	success: function(res) {
		saveRecord(20171103, 1);
	},
	cancel: function(res) {},
	fail: function(res) {
		alert(JSON.stringify(res));
	}
});
});